<?php

/**
 * This is the model class for table "b2b_order".
 *
 * The followings are the available columns in table 'b2b_order':
 * @property string $id
 * @property integer $center_id
 * @property integer $sub_center_id
 * @property integer $customer_id
 * @property string $customer_name
 * @property integer $customer_gender
 * @property string $order_time
 * @property integer $customer_certificate
 * @property string $customer_no
 * @property string $customer_mobile
 * @property string $customer_telephone
 * @property string $email
 * @property string $qq
 * @property integer $order_type
 * @property string $customer_company
 * @property integer $card_type
 * @property string $card_no
 * @property integer $order_item_type
 * @property string $order_item_id
 * @property integer $status
 * @property integer $price
 * @property string $exam_id
 * @property string $create_at
 * @property string $update_at
 */
class B2bOrder extends CActiveRecord {
    //体检状态定义
    //状态1为新预约，2为预约成功，3为完成体检，
    //4为预约完成预约日却没有体检，5为已取得电子版体检报告，
    //6用户取消预约，7体检中心取消预约，并有消息反馈，
    //8再次预约，9为团队预约,10企业管理员团队预约取消,11团约成功
    const GEREN_NEW = 1;
    const GEREN_SUCCESS = 2;
    const TJ_SUCCESS = 3;
    const TJ_CANCEL = 4;
    const TJ_REPORT = 5;
    const GEREN_CANCEL = 6;
    const GEREN_CANCEL_MSG = 7;
    const GEREN_REYUYUE = 8;
    const TUAN_NEW = 9;
    const TUAN_CANCEL = 10;
    const TUAN_SUCCESS = 11;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return B2bOrder the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'b2b_order';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('center_id, sub_center_id, customer_id, status', 'required'),
            array('center_id, sub_center_id, customer_id, customer_gender, customer_certificate, order_type, card_type, order_item_type, status, price', 'numerical', 'integerOnly' => true),
            array('customer_name', 'length', 'max' => 256),
            array('customer_no, exam_id', 'length', 'max' => 64),
            array('customer_mobile, customer_telephone, qq', 'length', 'max' => 20),
            array('email, customer_company, card_no', 'length', 'max' => 128),
            array('order_item_id', 'length', 'max' => 200),
            array('order_time, create_at, update_at', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, center_id, sub_center_id, customer_id, customer_name, customer_gender, order_time, customer_certificate, customer_no, customer_mobile, customer_telephone, email, qq, order_type, customer_company, card_type, card_no, order_item_type, order_item_id, status, price, exam_id, create_at, update_at', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
//                    'appointment' => array(self::HAS_MANY,'B2bPackageToCompany',array('company_id'=>'company_id','level'=>'level')),
            "center" => array(self::BELONGS_TO, 'B2bSubCenter', array("sub_center_id" => "id")),
            "ext_user" => array(self::BELONGS_TO, 'B2bExternalUser', array("ext_user_id" => "id")),
            "package" => array(self::BELONGS_TO, 'B2bPackage', array("order_item_id" => "id")),
            'telphone'=> array(self::BELONGS_TO, 'B2bUser', array("customer_id" => "id")),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'center_id' => 'Center',
            'sub_center_id' => 'Sub Center',
            'customer_id' => 'Customer',
            'customer_name' => 'Customer Name',
            'customer_gender' => 'Customer Gender',
            'order_time' => 'Order Time',
            'customer_certificate' => 'Customer Certificate',
            'customer_no' => 'Customer No',
            'customer_mobile' => 'Customer Mobile',
            'customer_telephone' => 'Customer Telephone',
            'email' => 'Email',
            'qq' => 'Qq',
            'order_type' => 'Order Type',
            'customer_company' => 'Customer Company',
            'card_type' => 'Card Type',
            'card_no' => 'Card No',
            'order_item_type' => 'Order Item Type',
            'order_item_id' => 'Order Item',
            'status' => 'Status',
            'price' => 'Price',
            'exam_id' => 'Exam',
            'create_at' => 'Create At',
            'update_at' => 'Update At',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search($centerid) {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;
        
        $criteria->addCondition("sub_center_id=$centerid");
        //不能够选择出团单预约的用户
        $criteria->addNotInCondition('order_type',array(1));
        if(!empty($this->status)&&!in_array($this->status,array(B2bOrder::GEREN_SUCCESS,  B2bOrder::TJ_SUCCESS,   B2bOrder::TJ_CANCEL))){
            //return false;
        }
        if($this->status == B2bOrder::GEREN_SUCCESS||$this->status == B2bOrder::TJ_CANCEL){
            $criteria->addCondition("status=$this->status");
        }elseif($this->status == B2bOrder::TJ_SUCCESS){
            $criteria->addInCondition("status", array(B2bOrder::TJ_SUCCESS,  B2bOrder::TJ_REPORT));
        }else{
            $criteria->addInCondition("status", array(B2bOrder::TJ_CANCEL,B2bOrder::GEREN_SUCCESS,B2bOrder::TJ_SUCCESS,  B2bOrder::TJ_REPORT));
        }
        
        if($this->customer_name != ""){
            $criteria->compare('customer_name', $this->customer_name, true);
        }
        if($this->customer_no != ""){
            $criteria->compare('customer_no', $this->customer_no, true);
        }
//        $criteria->addInCondition("status", $this->status);
//        $criteria->compare('id', $this->id, true);
//        $criteria->compare('sub_center_id', $this->sub_center_id);
//        $criteria->compare('customer_name', $this->customer_name, true);
//        $criteria->compare('order_time', $this->order_time, true);
//        $criteria->compare('customer_no', $this->customer_no, true);
//        $criteria->compare('customer_telephone', $this->customer_telephone, true);
//        $criteria->compare('email', $this->email, true);
//        $criteria->compare('qq', $this->qq, true);
//        $criteria->compare('order_type', $this->order_type);
//        $criteria->compare('customer_company', $this->customer_company, true);
//        $criteria->compare('card_type', $this->card_type);
//        $criteria->compare('status', $this->status);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'pagination' =>array('pageSize'=>30)
        ));
    }

    /**
     * 根据uid获取用户的用户所预定的健身中心的经纬度
     */
    public function getOrderCenterGps($uid) {
        $criteria = new CDbCriteria;
        $criteria->condition = "customer_id=:customer_id";
//            var_dump($uid);break;
        $criteria->params = array('customer_id' => $uid);
        $criteria->with = array("center");
        $ret = $this->findAll($criteria);
        if (empty($ret)) {
            return NULL;
        }
        return $ret;
    }

    /**
     * 预定团单
     */
    public function appointmentTuan($users, $yuyue) {
        //检测预约时间
        $time = $yuyue["time"];
        if (empty($time) || date_create($time) < date_create()) {
            return "不合适的日期";
        }
        $sql = <<<EOF
INSERT INTO  `marvel`.`b2b_order` (
`center_id` ,
`sub_center_id` ,
`sub_center_name` ,
`customer_id` ,
`ext_user_id` ,
`customer_name` ,
`customer_gender` ,
`order_time` ,
`customer_certificate` ,
`customer_no` ,
`order_type` ,
`customer_company` ,
`order_item_type` ,
`order_item_id` ,
`status` ,
`create_at` ,
`update_at`
)
VALUES (
:center_id,  :sub_center_id,  :sub_center_name,  '', :ext_user_id, :customer_name,
:customer_gender,  :order_time, :customer_certificate ,  :customer_no, 
1,:customer_company , 1 ,  :order_item_id,
'9', NOW( ) , NOW( )
);
EOF;
        $transaction = Yii::app()->db->beginTransaction();
        $comm = Yii::app()->db->createCommand($sql);


        $getcurrid = Yii::app()->db->createCommand("select last_insert_id() as id");
        $centers = array();
        $params = array();
        $tuan_order = array(); //按照体检中心保存团单信息
        try {
            //遍历所有的用户，为每一个用户单独在B2bOrder创建一条预约记录，所有预约状态为团队预约
            foreach ($users as $user) {
                //不可预约的用户直接过滤掉
                if ($user->statuscode != 0) {
                    //continue;
                }
                //根据套餐ID获取预约的体检中心
                if (!isset($yuyue["centers"][$user->package_id])) {
                    continue;
                }
                $center_id = $yuyue["centers"][$user->package_id];
                if (!isset($centers[$center_id])) {
                    $centers[$center_id] = B2bSubCenter::model()->findByPk($center_id);
                }
                //组装信息
                $params[":center_id"] = $centers[$center_id]->center_id;
                $params[":sub_center_id"] = $centers[$center_id]->id;
                $params[":sub_center_name"] = $centers[$center_id]->name;
                $params[":ext_user_id"] = $user->id;
                $params[":customer_name"] = $user->realname;
                $params[":customer_gender"] = $user->gender;
                $params[":customer_no"] = $user->customer_no;
                $params[":order_time"] = $time;
                $params[":customer_company"] = $user->company_name;
                $params[":customer_certificate"] = $user->customer_certificate;
                $params[":order_item_id"] = $user->package_id;
                $comm->execute($params);

                $ret = $getcurrid->query()->read();
                if ($ret["id"] == 0) {
                    //不应该啊不应该
                    throw new Exception("数据库异常");
                }

                if (!isset($tuan_order[$centers[$center_id]->id])) {
                    $tuan_order[$centers[$center_id]->id]["center_id"] = $centers[$center_id]->center_id;
                    $tuan_order[$centers[$center_id]->id]["order_count"] = 0;
                    $tuan_order[$centers[$center_id]->id]["company_id"] = $user->company_id;
                    $tuan_order[$centers[$center_id]->id]["customer_company"] = $user->company_name;
                    $tuan_order[$centers[$center_id]->id]["sub_center_name"] = $centers[$center_id]->name;
                    $tuan_order[$centers[$center_id]->id]["b2b_order_id"] = array();
                }

                array_push($tuan_order[$centers[$center_id]->id]["b2b_order_id"], $ret["id"]);
                $tuan_order[$centers[$center_id]->id]["order_count"]++;
                //标示为团检预约
                $user->statuscode = 4;
                $user->update();
            }
            //throw new Exception("数据库测试异常");
            foreach ($tuan_order as $key => $o) {
                $tuan = new B2bOrderTuan();
                $tuan->b2b_order_id = implode(",", $o["b2b_order_id"]);
                $tuan->order_time = $time;
                $tuan->center_id = $o["center_id"];
                $tuan->order_count = $o["order_count"];
                $tuan->adminuser = Yii::app()->user->getId();
                $tuan->customer_company = $o["customer_company"];
                $tuan->company_id = $o["company_id"];
                $tuan->customer_company = $o["customer_company"];
                $tuan->sub_center_id = $key;
                $tuan->statuscode = 1;
                $tuan->sub_center_name = $o["sub_center_name"];
                $tuan->create_at = new CDbExpression("NOW()");
                if (false === $tuan->save()) {
                    throw new Exception("数据库异常");
                }
            }
            $transaction->commit();
            return true;
        } catch (Exception $e) {
            $transaction->rollBack();
            return $e->getMessage();
        }
    }

    /*
     * 个单处理
     */

    public function proc($item,$order) {
        $transaction = Yii::app()->db->beginTransaction();
        try {
            if ($order["op"] == 0) {//通过
                if($item->ext_user !== null){
                    $item->ext_user->statuscode = B2bExternalUser::GEREN_YUYUED;
                    $item->ext_user->update();
                }
                $item->status = B2bOrder::GEREN_SUCCESS;
            } elseif ($order["op"] == 1) {//有反馈
                $t = date_create($order["time"]);
                if ($t < date_create()) {
                    throw new Exception("非法日期");
                }
                $item->etc = "建议您" . ($t->format("Y-m-d"))."进行体检";
                $item->status = B2bOrder::GEREN_CANCEL_MSG;
                //暂时此状态下打开用户可预约
                ////
                if($item->ext_user !== null){
                    $item->ext_user->statuscode = B2bExternalUser::YUYUE_ENABLE;
                    $item->ext_user->update();
                }
                ////
            } else {//完全关闭，用户可再次预约
                if($item->ext_user !== null){
                    $item->ext_user->statuscode = B2bExternalUser::YUYUE_ENABLE;
                    $item->ext_user->update();
                }
                $item->status = B2bOrder::GEREN_CANCEL;
            }
            $item->save();
            $transaction->commit();
            return true;
        } catch (Exception $exc) {
            $transaction->rollback();
            return $exc->getMessage();
        }
    }
    /*
     * 获取预约
     */

    public function getneworder(&$maxid, $subcenterid) {
        $criteria = new CDbCriteria;
        if ($maxid > 0) {
            $criteria->compare("id", ">" . $maxid);
        }
        $criteria->addCondition("sub_center_id=" . $subcenterid);
        $criteria->addInCondition("status", array(1, 8));

        $ret = $this->findAll($criteria);
        $items = array();
        foreach ($ret as $t) {
            if($t->id > $maxid){
                $maxid = $t->id;
            }
            $item["id"] = $t->id;
            $item["order_time"] = $t->order_time;
            $item["sub_center_name"] = $t->sub_center_name;
            $item["customer_company"] = $t->customer_company;
            $item["people_count"] = 1;
            $item["order_type"] = 1; //个单    
            array_push($items, $item);
        }
        return $items;
    }
    
    public function upstatus($id,$centerid,$status){
        $it = $this->findByAttributes(array("id"=>$id,"sub_center_id"=>$centerid));
        if(null === $it){
            return "错误的ID";
        }
        if($status == B2bOrder::GEREN_CANCEL&&$it->status == B2bOrder::GEREN_SUCCESS){
            $it->status = B2bOrder::GEREN_CANCEL;
        }elseif($status == B2bOrder::TJ_SUCCESS&&$it->status == B2bOrder::GEREN_SUCCESS){
            $it->status = B2bOrder::TJ_SUCCESS;
        }elseif($status == B2bOrder::TJ_CANCEL&&$it->status == B2bOrder::GEREN_SUCCESS){
            $it->status = B2bOrder::TJ_CANCEL;
        }else{
            return "不允许修改";
        }
        if($it->update() === true){
            return true;
        }else{
            return "数据库异常";
        }
    }
}